<!--
* description: 电池追溯
* author: hm
* createdDate: 2021
-->
<template>
  <section class="battery">
    <el-dialog
      v-dialogDrag
      :close-on-click-modal="true"
      title="电池追溯"
      :append-to-body="true"
      :visible="popupsVisibleBattery"
      width="70%"
      @close="closeEdit"
      @opened="open"
    >
      <dialogHeader
        slot="title"
        title="电池追溯"
        :style-type="$store.state.app.dialogType"
      />
      <div class="app-container app-container-table">
        <!-- 单表格模版页面 -->
        <one-table-template
          ref="multipleTable"
          v-loading="loading"
          :dynamic-buttons="tableButtons"
          :dynamic-components="tableComponents"
          :dynamic-table-cols="tableCols"
          :dynamic-form-fields="formField"
          :dynamic-table-defult-height="350"
          :dynamic-is-show-select="true"
          :dynamic-is-init-table="true"
          :dynamic-is-fix-choose="false"
          :dynamic-is-fix-index="false"
          :is-show-pagination="false"
          :dynamic-api-style="'restful'"
          :dynamic-page-size="20"
          :callback-obj="callbackObj"
        />
        <div class="el-pagination is-background">
          <el-pagination
            ref="oneTable.pageArea"
            :page-sizes="pageSizeArray"
            :page-size="dynamicPageSize"
            layout="prev, pager, next, sizes, ->, total"
            :prev-text="$t('sys.content.prevPage')"
            :next-text="$t('sys.content.nextPage')"
            :total="pages"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <edit
          :key="editPopupsKey"
          :dynamic-edit-row-data="editRowData"
          :popups-visible="editPopupsVisible"
          :popups-state="editPopupsState"
          :dynamic-api-style="'restful'"
          :edit-row-data="editRowData"
          :dispatch-number="dispatchNumber"
          @close="close"
          @numRefresh="numRefresh"
        />
      </div>
    </el-dialog>
  </section>
</template>
<script>
import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import { orgApis } from '@/api/caseManagementQuery'

export default {
  name: 'BatteryQuery',
  components: {
    OneTableTemplate,
    Edit: () => import('./edit'),
    dialogHeader: () => import('@/components/dialogHeader') // 弹窗标题
  },
  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],
  props: {
    popupsVisibleBattery: { type: Boolean, default: false },
    batteryData: { type: Object, default: () => ({}) }
  },
  data() {
    return {
      loading: false,
      pages: 0, //  分页总条数
      detailData: {},
      dispatchNumber: {},
      // apiConfig: orgApis.tracingPartsQuery, // ,
      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'controlBtn',
              label: '操作', // 操作
              codeField: 'orgName',
              width: null,
              align: 'center',
              isComponent: true,
              comps: [
                {
                  compKey: 'propKey0',
                  align: 'center',
                  labelName: '详情',
                  codeField: 'editControlBtn',
                  rowFileds: 'show:isCommit-1|0',
                  clickEvent: (index) => this.edit(index, 'edit'),
                  component: () => import('@/components/org/linkButton')
                },
                {
                  compKey: 'propKey1',
                  align: 'center',
                  labelName: '修改',
                  rowFileds: 'show:isCommit-0',
                  clickEvent: (index) => this.edit(index, 'detail'),
                  component: () => import('@/components/org/linkButton')
                }
              ]
            },
            {
              prop: 'dlrCode',
              label: '门店编码',
              align: 'center'
            },
            {
              prop: 'dlrFullName',
              label: '门店名称',
              align: 'center'
            },
            {
              prop: 'vin',
              label: 'VIN',
              align: 'center'
            },
            {
              prop: 'repairOrderCode',
              label: '派工单号',
              align: 'center'
            },
            {
              prop: 'replaceTypeName',
              label: '追溯件类别',
              align: 'center'
            },
            {
              prop: 'partsCode',
              label: '原追溯件编码',
              align: 'center'
            },
            {
              prop: 'newCode',
              label: '新件编码',
              align: 'center'
            },
            {
              prop: 'whereaboutsName',
              label: '去向单位名称',
              align: 'center'
            },
            {
              prop: 'whereaboutsCode',
              label: '去向单位统一社会信用代码',
              align: 'center'
            },
            {
              prop: 'createdDate',
              label: '登记日期',
              align: 'center'
            },
            {
              prop: 'creator',
              label: '登记人',
              align: 'center'
            }
          ],
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            // 库存状态
            {
              compKey: 'compKey1',
              labelName: '登记日期：',
              codeField: 'createdStartDate,createdEndDate',
              component: () =>
                import('@/components/org/datePicker/andtDatePicker'),
              type: 'YYYY-MM-DD',
              format: 'yyyy-MM-dd',
              dateOptionsType: '0',
              isMust: true,
              span: 6
            },
            // 车辆状态
            {
              compKey: 'compKey2',
              labelName: '门店编码：',
              codeField: 'dlrCode',
              component: () => import('@/components/ve/salesStore'),
              type: 'dropdownList',
              isMust: true,
              span: 6
            },
            {
              compKey: 'compKey3',
              labelName: '派工单号：',
              codeField: 'repairOrderCode',
              component: () => import('@/components/org/commonInput'),
              type: 'dropdownList',
              isMust: true,
              span: 6,
              disabled: true
            },
            {
              compKey: 'compKey4',
              labelName: 'VIN：',
              codeField: 'vin',
              component: () => import('@/components/org/commonInput'),
              type: 'dropdownList',
              isMust: true,
              span: 6
            }
          ],
      tableButtons: [
        {
          compKey: 'btnKey1',
          size: 'small',
          clickEvent: () => this.add(),
          name: 'add',
          position: 'left',
          text: '新增'
        },
        {
          conmpKey: 'btenKey2',
          type: 'primary',
          size: 'small',
          text: '查询',
          name: 'search',
          clickEvent: () => this.open(),
          position: 'right'
        },
        {
          compKey: 'btnKey6',
          size: 'small',
          icon: 'iconfont  icon-preservation',
          clickEvent: () => this.editSave(),
          text: '提交',
          disabled: false,
          position: 'left'
        },
        {
          conmpKey: 'btenKey5',
          size: 'small',
          icon: 'iconfont  icon-cancel',
          text: '删除',
          clickEvent: () => this.dele(),
          position: 'left'
        },
        // {
        //   conmpKey: "btenKey3",
        //   type: "primary",
        //   size: "small",
        //   text: "导出",
        //   name: "export",
        //   clickEvent: () => this.export(),
        //   position: "left",
        // },
        {
          conmpKey: 'btenKey4',
          size: 'small',
          text: '重置',
          name: 'reset',
          clickEvent: () => this.reset(),
          position: 'right'
        }
      ],
      formField: this.$utils.getFormField(this, {
        createdStartDate: '',
        createdEndDate: '',
        dlrCode: '',
        // repairOrderCode: "",
        vin: '',
        pagesize: this.dynamicPageSize,
        pageindex: 1
      }),
      callbackObj: {
        onCheckSelectChange: (selection) => {
          this.selectTable = selection
        }
      }
    }
  },
  methods: {
    getSelectable(row, index, ref) {
      return row['isCommit'] === '0'
    },
    numRefresh() {
      const that = this
      this.$nextTick(() => {
        // that.queryTable(1);
        that.open()
      })
    },
    open() {
      this.formField.repairOrderCode = this.batteryData.repairOrderCode
      const formList = JSON.parse(JSON.stringify(this.formField))
      this.loading = true
      this.$requestAPI({
        apiUrl: orgApis.tracingPartsQuery.APIUrl,
        variables: formList
        // variables: {
        // repairOrderCode: this.batteryData.repairOrderCode,
        // },
      }).then((res) => {
        if (res.result === '1') {
          this.loading = false
          this.pages = res.records
          this.$refs['multipleTable'].list = res.rows
        }
      })
    },

    // 关闭弹窗
    closeEdit() {
      this.$emit('close')
      this.popupsVisibleBattery = false
      this.$emit('update:popupsVisibleBattery', false)
    },

    close(type) {
      this.editPopupsVisible = type
    },
    edit(index, status) {
      this.editPopupsState = status
      this.editPopupsVisible = true
      this.editRowData = this.$utils.deepCopy(this.$refs['multipleTable'].list[index])
    },
    add() {
      this.dispatchNumber.repairOrderCode = this.formField.repairOrderCode
      this.editPopupsState = 'add'
      this.editPopupsVisible = true
    },
    // 选择分页事件
    handleSizeChange(val) {
      this.formField.pagesize = val
      this.formField.pageindex = 1
      this.$refs.multipleTable.listIndex.pageSize = val
      this.query()
    },
    // 当前页选中事件
    handleCurrentChange(val) {
      this.formField.pageindex = val
      this.$refs.multipleTable.listIndex.pageIndex = val
      this.query()
    },
    // 批量删除按钮
    dele() {
      if (!this.selectTable) {
        this.$message({
          message: '没有选中项',
          type: 'warn',
          duration: 1000
        })
        return
      }

      const tableList = this.selectTable.map((item) => {
        return Object.assign({}, { 'partsReplaceId': item.partsReplaceId })
      })
      const that = this
      const queryObj = {
        type: 'mutation',
        apiConfig: {
          ServiceCode: 'delTraceableParts',
          APIUrl:
            '/mp/e3sh/aftersale/WorkOrderManagementService/delTraceableParts.do'
        },
        variables: {
          list: tableList
        }
      }
      var paramD = this.$getParams(queryObj)
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          that.$message({
            message: '追溯件删除成功',
            type: 'success',
            duration: 1000
          })
          // that.queryTable(1)
          that.open()
        } else {
          // 删除失败
          that.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },
    // 批量提交按钮
    editSave() {
      if (!this.selectTable) {
        console.log(this.selectTable)
        this.$message({
          message: '没有选中项',
          type: 'warn',
          duration: 1000
        })
        return
      }

      const tableList = this.selectTable.map((item) => {
        return Object.assign({}, { 'partsReplaceId': item.partsReplaceId })
      })
      const that = this
      const queryObj = {
        type: 'mutation',
        apiConfig: {
          ServiceCode: 'submitTraceableParts',
          APIUrl:
            '/mp/e3sh/aftersale/WorkOrderManagementService/submitTraceableParts.do'
        },
        variables: {
          list: tableList
        }
      }
      var paramD = this.$getParams(queryObj)
      this.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          that.$message({
            message: '追溯件提交成功',
            type: 'success',
            duration: 1000
          })
          // that.queryTable(1)
          that.open()
        } else {
          // 提交失败
          that.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    }
  }
}
</script>
<style scoped>
</style>
